<?php

namespace backend\modules\rbac\controllers;

use backend\modules\base\controllers\BaseController;
use common\lib\Singleton;
use Yii;
use backend\modules\rbac\models\Menu;
use backend\modules\rbac\models\search\MenuSearch;
use yii\base\Exception;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * MenuController implements the CRUD actions for Menu model.
 */
class MenuController extends BaseController
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => ['login', 'error'],
                        'allow' => true,
                    ],
                    [
                        'actions' => ['index','create','view','update','addmenu','move'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all Menu models.
     * @return mixed
     */
    public function actionIndex()
    {
        if(!Menu::find()->one()){
            $newMenu = new Menu();
            $newMenu->url = 'site/index';
            $newMenu->name = '首页';
            $newMenu->icon_char = '';
            $newMenu->lft = 0;
            $newMenu->rgt = 1;
            $newMenu->save();
        }

        return $this->render('index');
    }

    /**
     * @return string
     */
//    public function actionAddmenu()
//    {
//        $post = Yii::$app->request->post();
//        $postData = $post['data'];
////                $menu = Menu::findOne(4);
//        if($postData) {
//            $newMenu = new Menu();
//            $newMenu->name = $postData['name'];
//            $newMenu->url = isset($postData['url'])?$postData['url']:'';
//            $newMenu->icon_char = isset($postData['icon_char'])?$postData['icon_char']:'file-code-o';
//            $e = $newMenu->tree_setTopNode();
////                    $e = $menu->tree_addChild($newMenu);
//            if($e) {
//                $message = ['code'=>200,'data'=>\common\widgets\MenuTree::widget()];
//                return json_encode($message);
//            }
//            $message = ['code'=>500,'message'=>'添加失败'];
//            return json_encode($message);
//        }
//    }

//    public function actionMove()
//    {
//        $post = Yii::$app->request->post();
//        $parent = isset($post['parent'])?$post['parent']:'';
//        $target = isset($post['target'])?$post['target']:'';
//        $prev = isset($post['prev'])?$post['prev']:'';
//        $next = isset($post['next'])?$post['next']:'';
//        $newMenu = Menu::findOne($target);
//        if(!$parent) {
//            $e = $newMenu->tree_setTopNode();
//        } else {
//            $parentMenu = Menu::findOne($parent);
//            $e = $newMenu->tree_moveNode($parentMenu);
//        }
//        if($e) {
////            $this->MoveCompli($newMenu,$prev);
//            $message = ['code'=>200,'data'=>\common\widgets\MenuTree::widget()];
//            return json_encode($message);
//        }
//
//        $message = ['code'=>200,'data'=>\common\widgets\MenuTree::widget()];
//        return json_encode($message);
//    }
//
//    public function MoveCompli($newMenu,$prev)
//    {
//        $parent = $newMenu->tree_directlyParent();
//        if($parent) {
//            $parentR = $parent->rgt;
//            $prevMenu = Menu::findOne($prev);
//            $prevR = $prevMenu->rgt;
//            $menuALL = Menu::find()->andWhere(["<",$parentR,'rgt'])->andWhere([">",$prevR,'rgt'])->all();
//            print_r($menuALL);exit;
//        } else  {
//
//        }
//    }

    /**
     * Displays a single Menu model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Menu model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Menu();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing Menu model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing Menu model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the Menu model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Menu the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Menu::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

    /**
     * Lists all Menu models.
     * @return mixed
     */
    public function actionMove()
    {
        $post = Yii::$app->request->post();

        $menu = Menu::findOne($post['target']);

        if(isset($post['parent']))
            $menu->parent = $post['parent'];
        else
            $menu->parent =null;

            if(isset($post['prev']))
                $menu->menu_prev = $post['prev'];
            else
                $menu->menu_prev =null;

            if(isset($post['next']))
                $menu->menu_next = $post['next'];
            else
                $menu->menu_next =null;

            $single = Singleton::getInstance();

            if($single)
            {
                $menu->multiSave($post);
                $single->ok();
            }
            $message = ['code'=>200,'data'=>\common\widgets\MenuTree::widget()];
            return json_encode($message);

    }

    public function actionAddmenu()
    {
        try {
            $post = Yii::$app->request->post();
            $postData = $post['data'];
            $menu = new Menu();
            $menu->name = $postData['name'];
            $menu->url = isset($postData['url'])?$postData['url']:'';
            $menu->icon_char = isset($postData['icon_char'])?$postData['icon_char']:'file-code-o';
            $menu->parent =null;
            $menu->multiSave($post);
        } catch (Exception $e) {
            print_r($e->getMessage());exit;
        }
        $message = ['code'=>200,'data'=>\common\widgets\MenuTree::widget()];
        return json_encode($message);
    }

}
